package com.yomahub.liteflow.example.threadproject;

import java.util.concurrent.*;

public class SingletonThreadPool {

    private volatile static SingletonThreadPool instance;
    private ThreadPoolExecutor threadPool;
    private boolean isResetRequested; // 标记是否需要重置线程池

    private SingletonThreadPool() {
        // 假设我们创建一个核心线程数为5、最大线程数也为5、无界队列的线程池
        threadPool = new ThreadPoolExecutor(
                5, // 核心线程数
                5, // 最大线程数
                60L, // 空闲线程存活时间
                TimeUnit.SECONDS, // 时间单位
                new LinkedBlockingQueue<Runnable>() // 工作队列
        );
    }

    public static SingletonThreadPool getInstance() {
        if (instance == null || instance.isResetRequested) { // 检查实例是否为空或是否需要重置
            synchronized (SingletonThreadPool.class) {
                if (instance == null || instance.isResetRequested) {
                    if (instance != null) {
                        instance.shutdown(); // 如果需要重置，则先关闭旧的线程池
                    }
                    instance = new SingletonThreadPool();
                    instance.isResetRequested = false; // 创建新线程池后重置标记
                }
            }
        }
        return instance;
    }

    public void execute(Runnable task) {
        if (threadPool != null && !threadPool.isShutdown()) {
            threadPool.execute(task);
        } else {
            throw new IllegalStateException("线程池已关闭或未初始化");
        }
    }

    // 添加重置线程池的方法
    public void requestReset() {
        if (instance != null) {
            instance.isResetRequested = true;
        }
    }

    public boolean isShutdown() {
        if (threadPool != null) {
            return threadPool.isShutdown();
        }
        return true;
    }

    public boolean isTerminated() {
        if (threadPool != null) {
            return threadPool.isTerminated();
        }
        return false;
    }

    // 其他必要的线程池管理方法
    public void shutdown() {
        if (threadPool != null) {
            threadPool.shutdown();
        }
    }

    // ...
}
